package com.game.customertextview;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by xiabing-wineti on 2017/1/12.   更改字体颜色
 */

public class MuiltiColorTextView extends TextView {
    private int mStart; //更改颜色第一个位置
    private int mEnd;  //更改颜色第二个位置
    private int mTextColor; //需要更改的颜色
    private SpannableStringBuilder mStyle;
    private boolean flag; //字体颜色是否有两个
    private int mSecondStart; //更改第二个颜色第一个位置
    private int mSecondEnd; //更改第二个颜色第二个位置
    private int mTextColor2;  //需要更改的颜色
    LogUtil log=LogUtil.getInstance();

    public MuiltiColorTextView(Context context) {
        this(context, null);
    }

    public MuiltiColorTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public MuiltiColorTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context,attrs);
    }

    public void initView(Context context,AttributeSet attrs){
        TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.MultiTextColor);
        mStart = tArray.getInteger(R.styleable.MultiTextColor_text_start, 0);
        mEnd = tArray.getInteger(R.styleable.MultiTextColor_text_end, 0);
        mTextColor = tArray.getInteger(R.styleable.MultiTextColor_text_color, 0);
        tArray.recycle();
    }

    public void setTextColorFirst(int mTextColor){
        this.mTextColor=mTextColor;
    }

    public void setTextColorSecond(int mTextColor){
        this.mTextColor2=mTextColor;
    }


    public void setTextFirstIndex(int start,int end){
        this.mStart=start;
        this.mEnd=end;
    }

    public void setTextSecondIndex(int start,int end){
        this.mSecondStart=start;
        this.mSecondEnd=end;
    }

    public void setFlag(boolean flag){ //true 两个 false 一个
        this.flag=flag;
    }

    public void updateText() {
        String str=getText().toString();
        if (str != null){
            if(flag){ //两个
                if(mEnd<mSecondStart&&mSecondEnd<str.length()){
                    mStyle = new SpannableStringBuilder(str);
                    mStyle.setSpan(new ForegroundColorSpan(mTextColor), mStart, mEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    mStyle.setSpan(new ForegroundColorSpan(mTextColor2), mSecondStart, mSecondEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }
                setText(mStyle);
            }else{ //一个
                mStyle = new SpannableStringBuilder(str);
                if(mEnd<=str.length()){
                    mStyle.setSpan(new ForegroundColorSpan(mTextColor), mStart, mEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }
                setText(mStyle);
            }
        }

    }
}



